package com.keray.common.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

// 图片验证码
public class ImageCode {
    static {
        System.setProperty("java.awt.headless", "true");
    }

    public final static String REQUESTION_KEY = "image-code";

    public static BufferedImage image(String code, int width, int height, int red, int green, int blue) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        g.setColor(new Color(red, green, blue));
        g.fillRect(0, 0, width, height);
        g.setFont(new Font("Arial", Font.PLAIN, 18));
        g.setColor(new Color(134, 150, 242));
        Random random = new Random();
        for (int i = 0; i < 50; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(30);
            int yl = random.nextInt(30);
            g.drawLine(x, y, x + xl, y + yl);
        }
        for (int i = 0; i < code.length(); i++) {
            g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
            g.drawString(code.substring(i, i + 1), 15 * i + 3, 18);
        }
        g.dispose();
        return image;
    }

    public static BufferedImage image(String code, int red, int green, int blue) {
        return image(code, 75, 25, red, green, blue);
    }

    public static BufferedImage image(String code) {
        return image(code, 255, 255, 255);
    }
}
